package com.leyou.common.advice;

import com.leyou.common.exception.LyException;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

@Slf4j
@Aspect
@Component
public class CommonLogAdvice {

    @Around("within(@org.springframework.stereotype.Service *)||" +
            "within(com.baomidou.mybatisplus.extension.service.IService+)") //带用@Service的注解都可以被记录日志
    public Object handleExceptionLog(ProceedingJoinPoint jp) throws Throwable {

        try {
            log.debug("{}方法准备调用，参数为{}",jp.getSignature(),jp.getArgs());//在目标方法执行之前记录日志//在目标方法执行之前记录日志
            Object obj = jp.proceed();//执行目标方法
            log.debug("{}方法执行完成",jp.getSignature());
            return obj;
        } catch (Throwable throwable) { //出现异常记录日志
            log.debug("{}方法执行出现异常,异常原因{}",jp.getSignature(),throwable.getMessage(),throwable);
            //判断异常是否为 LyException,如果是直接抛出
            if (throwable instanceof LyException){
                throw throwable;
            }else {
                //不是则转为
                throw new LyException(500,throwable);
            }
        }
    }
}
